package net.pws.oos.security;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.pws.common.security.SecurityContext;
import net.pws.common.security.filter.AbstractAuthenticateFilter;

public class DruidAccessCheckFilter extends AbstractAuthenticateFilter {
    
    private String protectedUrl = "/druid";
    
    public DruidAccessCheckFilter() {
        super();
    }
    
    public DruidAccessCheckFilter(String protectedUrl) {
        super();
        this.protectedUrl = protectedUrl;
    }
    
    public String getProtectedUrl() {
        return protectedUrl;
    }
    
    public void setProtectedUrl(String protectedUrl) {
        this.protectedUrl = protectedUrl;
    }
    
    protected boolean required(HttpServletRequest request,
                               HttpServletResponse response) {
        String druidUrl = request.getContextPath() + protectedUrl;
		return request.getRequestURI().startsWith(druidUrl);
    }
    
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain) throws IOException,
                                           ServletException {
        
        if (!(request instanceof HttpServletRequest)) {
            throw new ServletException("Can only process HttpServletRexquest");
        }
        
        if (!(response instanceof HttpServletResponse)) {
            throw new ServletException("Can only process HttpServletResponse");
        }
        
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        if (!required(httpRequest, httpResponse)) {
            chain.doFilter(request, response);
            return;
        }
        
        if (!SecurityContext.getContext().hasPrivileged()) {
            sendRedirect(httpRequest, httpResponse, getNoPermissionPage());
            return;
        }
        
        chain.doFilter(request, response);
    }
    
}
